package main

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v2"
)

type Config struct {
	Listening struct {
		Address string `yaml:"address"`
		Port    int    `yaml:"port"`
	} `yaml:"listening"`
	HmacPwd string `yaml:"hmacPwd"`
}

const configFilename = "./config.yaml"

func ReadConfig() (*Config, error) {
	buf, err := os.ReadFile(configFilename)
	// buf, err := ioutil.ReadFile(configFilename)
	if err != nil {
		return nil, fmt.Errorf("ioutil.ReadFile failed, %v", err)
	}
	cfg := &Config{}
	err = yaml.Unmarshal(buf, cfg)
	if err != nil {
		return nil, fmt.Errorf("yaml.Unmarshal failed, %v", err)
	}
	return cfg, nil
}

func WriteConfig(cfg *Config) error {
	buf, err := yaml.Marshal(cfg)
	if err != nil {
		return fmt.Errorf("yaml.Marshal failed, %v", err)
	}
	err = os.WriteFile(configFilename, buf, os.ModePerm)
	// err = ioutil.WriteFile(configFilename, buf, os.ModePerm)
	if err != nil {
		return fmt.Errorf("ioutil.ReadFile failed, %v", err)
	}
	return nil
}
